package com.simple.accounting.activity;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.simple.accounting.R;
import com.simple.accounting.db.AccountBean;
import com.simple.accounting.db.DBManager;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class SettingActivity extends BaseActivity implements View.OnClickListener{

    /*设置多次点击的最小间隔*/
    public static final int MIN_CLICK_DELAY_TIME = 1000;
    /*上次点击时间*/
    private long lastClickTime = 0;
    HSSFWorkbook workbook;
    List<AccountBean> accountBeans;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        try {
            workbook = new HSSFWorkbook(new FileInputStream(new File(Environment.getExternalStorageDirectory(), "account.xls")));
        } catch (IOException e) {
            e.printStackTrace();
        }
        accountBeans = new ArrayList<>();

        ImageView iv = findViewById(R.id.setting_iv_back);
        TextView tvExport = findViewById(R.id.setting_export_record);
        TextView tvImport = findViewById(R.id.setting_import_record);
        TextView tvClear = findViewById(R.id.setting_tv_clear);
        TextView tvPwd = findViewById(R.id.changePwd);
        Button btn = findViewById(R.id.logoff);

        iv.setOnClickListener(this);
        tvExport.setOnClickListener(this);
        tvImport.setOnClickListener(this);
        tvClear.setOnClickListener(this);
        tvPwd.setOnClickListener(this);
        btn.setOnClickListener(this);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.setting_export_record:
                showExportDialog();
                break;
            case R.id.setting_import_record://从本地文件导入数据
                showImportDialog();
                break;
            case R.id.setting_iv_back:
                finish();
                break;
            case R.id.setting_tv_clear:
                showDeleteDialog();
                break;
            case R.id.changePwd:
                long currentTime = Calendar.getInstance().getTimeInMillis();
                if (currentTime - lastClickTime >MIN_CLICK_DELAY_TIME){
                    lastClickTime = currentTime;
                    Intent intent = new Intent(SettingActivity.this,ChangePwdActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.logoff:
                showLogoffDialog();
                break;

        }
    }

    /*退出功能的实现*/
    private void showLogoffDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("退出登录")
                .setMessage("确定退出登录吗？")
                .setNegativeButton("取消",null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        clearUserInfoWithSP();
                        Intent intent = new Intent("com.simple.accounting.logout");
                        sendBroadcast(intent);
                    }
                });
        builder.create().show();
    }

    private void showExportDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("您确定要导出所有账单记录吗？")
                .setNegativeButton("取消",null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread(){
                            @Override
                            public void run() {
                                exportData();
                            }
                        }.start();
                    }
                });
        builder.create().show();
    }

    private void showImportDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("您确定要从本地文件导入账单记录吗？")
                .setNegativeButton("取消",null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread(){
                            @Override
                            public void run() {
                                getCellData();
                            }
                        }.start();
                    }
                });
        builder.create().show();
    }

    private void showDeleteDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("您确定要删除所有的账单记录？\n注意：删除后无法恢复，请慎重选择！")
                .setNegativeButton("取消",null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DBManager.deleteAllAccount();
                        Toast.makeText(SettingActivity.this,"删除成功！",Toast.LENGTH_SHORT).show();
                    }
                });
        builder.create().show();
    }

    private void clearUserInfoWithSP() {
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("isChecked",false);//editor是对map进行封装 限制用户输入的类型
        editor.putString("username","");
        editor.putString("pw","");
        editor.commit();//提交commit
    }

    private void exportData(){
        HSSFWorkbook workbook = new HSSFWorkbook();
        List<AccountBean> accountBeans = DBManager.getAllAccountListFromAccountTb();;
        HSSFSheet mSheet = workbook.createSheet("account");;

        createExcelHead(mSheet);
        for (AccountBean accountBean : accountBeans) {
            createCell(accountBean.id, accountBean.typename,accountBean.sImageId,accountBean.remarks,accountBean.money,
                    accountBean.time,accountBean.year,accountBean.month,accountBean.day,accountBean.kind, mSheet);
        }

        try {
            File xlsFile = new File(Environment.getExternalStorageDirectory(), "account.xls");
            workbook.write(xlsFile);
            workbook.close();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(SettingActivity.this,"数据已保存至"+Environment.getExternalStorageDirectory()+"文件夹下"
                            ,Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void createCell(int id, String typename, int sImageId, String remarks, float money, String time, int year, int month, int day, int kind, HSSFSheet sheet) {
        HSSFRow dataRow  =sheet.createRow(sheet.getLastRowNum()+1);
        dataRow.createCell(0).setCellValue(id);
        dataRow.createCell(1).setCellValue(typename);
        dataRow.createCell(2).setCellValue(sImageId);
        dataRow.createCell(3).setCellValue(remarks);
        dataRow.createCell(4).setCellValue(money);
        dataRow.createCell(5).setCellValue(time);
        dataRow.createCell(6).setCellValue(year);
        dataRow.createCell(7).setCellValue(month);
        dataRow.createCell(8).setCellValue(day);
        dataRow.createCell(9).setCellValue(kind);
    }

    // 创建Excel标题行，第一行。
    private void createExcelHead(HSSFSheet mSheet) {
        HSSFRow headRow = mSheet.createRow(0);
        headRow.createCell(0).setCellValue("id");
        headRow.createCell(1).setCellValue("typename");
        headRow.createCell(2).setCellValue("sImageId");
        headRow.createCell(3).setCellValue("remarks");
        headRow.createCell(4).setCellValue("money");
        headRow.createCell(5).setCellValue("time");
        headRow.createCell(6).setCellValue("year");
        headRow.createCell(7).setCellValue("month");
        headRow.createCell(8).setCellValue("day");
        headRow.createCell(9).setCellValue("kind");
    }

    private void getCellData(){
        HSSFSheet sheet = workbook.getSheet("account");
        int totalRowCount  = sheet.getPhysicalNumberOfRows();
        accountBeans.clear();
        //去除excel表格第一行表头
        for(int i=1; i<totalRowCount; i++){
            HSSFRow row = sheet.getRow(i);
            int id = (int)Float.parseFloat(row.getCell(0).toString());
            String typename = row.getCell(1).toString();
            BigDecimal bigDecimal = new BigDecimal(row.getCell(2).toString());
            int sImageId = (int) Integer.parseInt(bigDecimal.toPlainString());
            String remarks = row.getCell(3).toString();
            float money = Float.parseFloat(row.getCell(4).toString());
            String time = row.getCell(5).toString();
            int year = (int)Float.parseFloat(row.getCell(6).toString());
            int month = (int)Float.parseFloat(row.getCell(7).toString());
            int day = (int)Float.parseFloat(row.getCell(8).toString());
            int kind = (int)Float.parseFloat(row.getCell(9).toString());

            AccountBean bean = new AccountBean(id,typename,sImageId,remarks,money,time,year,month,day,kind);
            accountBeans.add(bean);
        }
        saveAccountToDB(accountBeans);
    }

    public void saveAccountToDB(List<AccountBean> importList){
        if(importList.size() > 0){
            //读取数据库中已经存在的数据
            List<AccountBean> existList = DBManager.getAllAccountListFromAccountTb();
            if(existList.size() > 0){

                for(int i=0; i<importList.size(); i++){
                    AccountBean importBean = importList.get(i);
                    boolean isExist = false;
                    for(int j=0; j<existList.size(); j++){
                        isExist = importBean.getId() == existList.get(j).getId() ? true : false;
                        if(isExist) break;//已经存在
                    }

                    if(!isExist)
                        DBManager.insertItemToAccountTb(importList.get(i));

                }
            }else {
                for(AccountBean bean : importList){
                    DBManager.insertItemToAccountTb(bean);
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(SettingActivity.this,"数据从"+Environment.getExternalStorageDirectory()+"文件夹导入成功！",Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}
